import Qt 4.7
import QtWebKit 1.0
import "config.js" as Options

Rectangle {
    property variant model
    property int current: model.current
    property alias rating: userRating.rating
    property variant history: []
    property int history_index: 0

    signal revealed

    function reveal() {
        answer.visible = false
        summary.visible = false
        model.current = -1
        history = []
        history_index = 0
    }

    function inHistory(index) {
        return history.some(function(current_index) {
            return index === current_index
        })
    }

    function isValidRating(rating) {
        return rating === 0 || rating === undefined || rating > filter.rating
    }

    // Get indicies (in terms of model) of unfiltered couplets not in history
    function getAvailable() {
        var result = []
        for(var index = 0; index < model.count; index += 1) {
            var in_history = inHistory(index)
            var rating = model.rating(index)

            if(!in_history && isValidRating(rating)) {
                result.push(index)
            }
        }
        return result
    }

    function getNextInGroup(group_id, group_pos) {
        var group = model.findAll({groupId: group_id})
        var min_index, min_pos
        for(var i = 0; i < group.length; i += 1) {
            var index = group[i]
            var item = model.get(index)
            if(item.groupPos <= group_pos) {
                continue
            }
            if(!isValidRating(model.rating(index))) {
                continue
            }
            if(min_pos === undefined || min_pos > item.groupPos) {
                min_index = index
                min_pos = item.groupPos
            }
        }
        console.log(group_id, group_pos, JSON.stringify(group), min_index)
        return min_index
    }

    function selectCouplet() {
        if(history_index < history.length - 1) {
            history_index += 1
            var index = history[history_index]
            return index
        }

        if(history.length > 0) {
            var item_index = history[history.length-1]
            var item = model.get(item_index)
            if(item.groupId !== null && item.groupId !== undefined) {
                var next_in_group_index = getNextInGroup(item.groupId, item.groupPos)
                if(next_in_group_index !== null && next_in_group_index !== undefined) {
                    return next_in_group_index
                }
            }
        }

        var available = getAvailable()
        if(available.length === 0) {
            //Done going through again
            history = []
            history_index = 0
            available = getAvailable();
            if(available.length > 0) {
                summary.visible = true
            }
        }

        var available_index = Math.floor(Math.random() * available.length)
        var couplet_index = available[available_index]
        var item = model.get(couplet_index)
        if(item.groupId !== null && item.groupId !== undefined) {
            couplet_index = getNextInGroup(item.groupId, 0)
        }
        return couplet_index
    }

    function next() {
        var next = selectCouplet()
        if(next === model.current) {
            model.current = -1
        }
        model.current = next
    }

    function back() {
        if(history.length >= history_index - 1 && history_index - 1 >= 0) {
            history_index -= 1
            var index = history[history_index]
            model.current = index
        }
    }

    onCurrentChanged: {
        question.text = model.get(current).question
        answer.text = model.get(current).answer
        question.image = model.get(current).image
        rating = model.rating(current) || 0
        answer.visible = false
        answer.redraw()

        if(!inHistory(current)) {
            var tmp = history
            tmp.push(current)
            history = tmp
            history_index = history.length - 1
        }
    }

    anchors.fill: parent

    Rectangle {
        id: title
        width: parent.width
        height: 40
        z: 4

        Button {
            id: buttonDialogs
            anchors.bottom: parent.bottom
            anchors.left: parent.left
            anchors.rightMargin: 5
            text: "Categories"
            onClicked: {
                window.state = "showDialogs";
                question.text = "Loading..."
                question.image = ""
            }
        }

        Text {
            text: model.dialogName(model.getDialogIndex())
            font.pixelSize: parent.height * 0.6
            anchors.left: buttonDialogs.right
            anchors.verticalCenter: parent.verticalCenter
            anchors { rightMargin: 10; leftMargin: 10; }
        }

        Button {
            text: "Filter" + " (" + filter.rating + ")"
            anchors.right: parent.right
            anchors.top: parent.top
            anchors.bottom: parent.bottom

            onClicked: {
                filter.visible = !filter.visible
            }
        }

        Rectangle {
            border.width: 1
            border.color: "#000000"
            height: 1
            width: parent.width
            anchors.bottom: parent.bottom
            radius: 1
        }
    }

    Rectangle {
        id: filter

        property alias rating: filterRating.rating

        visible: false
        width: 260
        height: 90
        border.width: 1
        border.color: "#000000"
        anchors.right: title.right
        anchors.top: title.bottom
        z: 4

        Button {
            id: buttonClose
            text: "X"
            width: 30
            anchors.top: parent.top
            anchors.right: parent.right

            onClicked: {
                parent.visible = false
            }
        }

        Text {
            text: "Hide all exactly or below"
            font.pixelSize: 20
            anchors { top: buttonClose.top; right: buttonClose.left; left: parent.left }
            anchors.leftMargin: 5
        }

        RatingSystem {
            id: filterRating
            anchors.bottom: parent.bottom
            anchors.left: parent.left
            anchors.leftMargin: 10
        }
    }

    WebView {
        id: question

        property string text
        property string image
        property string image_html

        onImageChanged: {
            if(image !== undefined) {
                var src = image.replace("http://localhost:8000", Options.server || "http://127.0.0.1")
                image_html = "<img src=" + src + "/>"
            }
        }

        settings.defaultFontSize: 28
        width: parent.width
        height: 200
        html: text + image_html
        anchors.top: title.bottom
    }

    WebView {
        id: answer

        property string text

        function redraw() {
            var w = width
            width = 0
            width = w
        }

        settings.defaultFontSize: 28
        anchors.top: question.bottom
        width: parent.width
        preferredHeight: 200
        html: text
    }

    Button {
        id: buttonReveal
        anchors.top: question.bottom
        anchors.left: question.left
        text: "Reveal answer"
        visible: !answer.visible
        onClicked: {
            answer.visible = true
            revealed()
        }
    }

    Button {
        id: buttonNext
        anchors.bottom: progress.top
        anchors.right: parent.right
        text: "Next question"
        onClicked: {
            next()
        }
    }

    Button{
        id:backButton
        anchors.bottom: progress.top
        anchors.right: buttonNext.left
        anchors.rightMargin: 5
        visible: history_index > 0
        text: "Back"
        onClicked:{
            back()
        }
    }

    RatingSystem {
        id: userRating

        anchors.bottom: buttonNext.top
        anchors.right: parent.right
        anchors.bottomMargin: 10
        anchors.rightMargin: 10
    }

    ProgressBar {
        id: progress
        position: history_index + 1
        total: history.length + getAvailable().length

        anchors { right: parent.right; bottom: parent.bottom; left: parent.left; }
    }

    DialogSummary {
        id: summary
        model: parent.model
        visible: false
    }

}
